// packageI/storePriceTag/storePriceTagIndex/storePriceTagIndex.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsPopupShow: false,
    themeColor: '#f14e4e',
    store_id: '',
    goodsId: '',
    cancelClick: false,
    addShow:false,
    imgPath: app.globalData.imgPath,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          }
          if (chil_arr[0] == "id") {
            this.setData({
              goodsId: chil_arr[1]
            })
            this.getGoodsDetail(this.data.goodsId)
          }
          if (chil_arr[0] == "store_id") {
            this.setData({
              store_id: chil_arr[1]
            })
            this.getStoreInfo();
            // 获取购物车列表
            this.getCart();
          }
        }
      }
    }
    if (options.store_id) {
      this.setData({
        store_id: options.store_id
      })
      this.getStoreInfo();
      // 获取购物车列表
      this.getCart();
    }
    if(options.id){
      this.setData({
        goodsId:options.id
      })
      this.getGoodsDetail(this.data.goodsId)
    }
    wx.setNavigationBarTitle({
      title: '自助买单',
    })
    wx.getStorage({
      key: 'yz_basic_info',
      success: (res) => {
        this.setData({
          themeColor: res.data.theme_color,
        });
      }
    });
  },
  toOrderChild(){
    if(this.data.goodsCarts.length <= 0) {
      app.tips('购物车暂无商品')
      return
    }
    this.setData({
      goodsPopupShow: false,
      goodsId: '',
    })
    this.goodsOrder();
  },
  closeShow() {
    this.setData({
      goodsPopupShow: false,
      goodsId: ''
    })
  },
  continueCode(){
    this.closeShowAdd();
    this.scanCode();
  },
  closeShowAdd(){
    this.setData({
      goodsPopupShow: false,
      goodsId: '',
      addShow:false
    })
  },
  addPopupClose(){
    this.setData({
      addShow:false,
    })
  },
  CutTap(e) {
    // 修改购物车数量
    if (this.data.cancelClick) return
    let good = e.currentTarget.dataset.good;
    let id = good.id;
    // 数量减少
    this.updateCartRequest(id, '-1')
  },
  AddTap(e) {
    console.log(e)
    let good = e.currentTarget.dataset.good;
    let tag = e.currentTarget.dataset.tag
    this.addCart(good, tag)
  },
  updateCartRequest(id, num,tag) {
    wx.showLoading({
      title: '加载中',
    })
    console.log(id, num)
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.updateNum');
    urlStr += '&id=' + id;
    urlStr += '&num=' + num;
    urlStr += '&store_id=' + this.data.store_id;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        wx.hideLoading()
        if (res.result == 1) {
          if (num < 0) {
            this.setData({
              popNum: this.data.popNum - 1
            });
          } else {
            this.setData({
              popNum: this.data.popNum + 1
            });
          }
          if(tag == 'goodPopup'){
            this.setData({
              addShow:true
            })
          }
          this.getCart();
          this.data.cancelClick = false;
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
          this.getCart();
          this.data.cancelClick = false;
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // 商品详情弹窗添加购物车
  childAddCart(e) {
    let good = e.detail.goodsInfo;
    let optionsId = e.detail.optionsId;
    let goodsCount = e.detail.goodsCount;
    let exist = null; //用来判断购物车列表是否已经有这个商品规格的
    if (!optionsId) {
      // 单规格
      for (let i = 0; i < this.data.carts.length; i++) {
        if (this.data.carts[i].goods_id == good.id) {
          exist = i;
        }
      }
      if (exist == null) {
        //没有规格,并且购物车列表没有这个商品 addCart 只能数量只能加1
        // console.log('并且购物车列表没有这个商品')
        this.addCart(good, 'goodPopup', goodsCount, optionsId)
      } else {
        //没有规格,并且购物车列表有这个商品
        // console.log('没有规格,并且购物车列表有这个商品',goodsCount,this.data.carts[exist].total)
        let addNum = (Number(goodsCount) + Number(this.data.carts[exist].total)) - Number(this.data.carts[exist].total);
        this.updateCartRequest(this.data.carts[exist].id, addNum,'goodPopup');
      }
    } else {
      // 有规格
      for (let i = 0; i < this.data.carts.length; i++) {
        if (this.data.carts[i].option_id == optionsId) {
          exist = i;
        }
      }
      if (exist == null) {
        //有规格 并且购物车列表没有有这个商品
        // console.log('并且购物车列表没有这个商品')
        this.addCart(good, 'goodPopup', goodsCount, optionsId)
      } else {
        //有规格,并且购物车列表有这个商品
        // console.log('有规格,并且购物车列表有这个商品',goodsCount,this.data.carts[exist].total)
        let addNum = (Number(goodsCount) + Number(this.data.carts[exist].total)) - Number(this.data.carts[exist].total);
        this.updateCartRequest(this.data.carts[exist].id, addNum,'goodPopup');
      }
    }
  },
  changeNum(e) {
    let oldNum = e.currentTarget.dataset.total;
    let nowNum = e.detail.value;
    let ind = e.currentTarget.dataset.ind;
    let goodsCartsData = this.data.carts[ind];
    if (nowNum < 0) {
      wx.showToast({
        icon: 'none',
        title: "商品数量不能为负数",
        duration: 1500
      });
      this.data.carts[ind].total = oldNum;
      this.setData({
        carts: this.data.carts
      })
      return
    }
    if (nowNum < oldNum) {
      let lowerNum = oldNum - nowNum;
      this.updateCartRequest(goodsCartsData.id, -lowerNum);
    } else if (nowNum > oldNum) {
      let addNum = Number(nowNum) - Number(oldNum);
      this.updateCartRequest(goodsCartsData.id, addNum);
    }
  },
  // 添加购物车
  addCart(goods, tag, total, optionsId) {
    console.log(goods)
    let id = "";
    if (tag === "cart") {
      id = goods.goods_id;
    } else {
      id = goods.id
    }
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.store');
    urlStr += '&goods_id=' + id;
    if (tag == "cart") {
      urlStr += '&option_id=' + (goods.option_id ? goods.option_id : 0);
      urlStr += '&total=1';
    } else {
      urlStr += '&option_id=' + optionsId;
      urlStr += '&total=' + total;
    }
    urlStr += '&store_id=' + this.data.store_id;
    wx.showLoading({
      title: '加载中',
    })
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        wx.hideLoading()
        if (res.result == 1) {
          if(tag == 'goodPopup'){
            this.setData({
              addShow:true
            })
          }
          this.getCart();
        } else {
          this.getCart();
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // 购物车全部清空
  clearCart() {
    var that = this;
    var destroyCarts = [];
    this.data.carts.forEach(item => {
      destroyCarts.push(item.id);
    });
    if(destroyCarts.length <= 0) return
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.destroy');
    urlStr += '&store_id=' + this.data.store_id;
    urlStr += '&ids=' + destroyCarts;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          that.getCart();
          that.setData({
            popNum: 0
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // 单独更新购物车列表数据
  getCart() {
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.index');
    app._postNetWork({
      url: urlStr,
      data: {
        store_id: this.data.store_id
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if (res.result == 0) return;
          console.log(res.data)
          this.getFirstCart(res.data);
        } else {
          wx.showToast({
            title: res.msg,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  // 初始化获取门店购物车和门店信息
  getStoreInfo() {
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.store.get-store-info.get-stores-details');
    app._postNetWork({
      url: urlStr,
      data: {
        store_id: this.data.store_id
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if (res.result == 0) return;
          this.setData({
            storeInfo: res.data
          })
          // this.getFirstCart(res.data.member_cart);
        } else {
          wx.showToast({
            title: res.msg,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  // 处理购物车数据
  getFirstCart(data) {
    this.setData({
      carts: data,
      goodsCarts: [],
      cartsNum: 0,
      cartsTotal: 0
    });
    console.log(data,this.data.carts)
    let arrObj = {};
    this.data.carts.forEach(item => {
      arrObj[item.goods_id] = item;
      if(item.is_failure == 0){
        this.data.cartsTotal += (item.total * item.goods.price);
      }
      this.setData({
        cartsNum: this.data.cartsNum + item.total
      });
    });
    this.setData({
      goodsCarts: this.data.carts.length > 0 ? arrObj : [],
      goodsCartsTotal: this.calculateTotal(this.data.carts),
      cartsTotal: parseFloat(this.data.cartsTotal).toFixed(2)
    });
    console.log(this.data.carts,this.data.goodsCarts, '处理购物车数据')
  },
  //不同规格的同一商品求和
  calculateTotal(arr) {
    let newArr = []; // 保存求和后的购物车数量列表
    let temp = {};
    let newArr2 = {};
    for (let i in arr) {
      let key = arr[i].goods_id;
      if (temp[key]) {
        temp[key].total = temp[key].total + arr[i].total; //id相同则把数量相加
      } else {
        temp[key] = {};
        temp[key].goods_id = arr[i].goods_id;
        temp[key].total = arr[i].total;
      }
    }
    for (let k in temp) {
      newArr.push(temp[k]);
    }
    newArr.forEach(item => {
      newArr2[item.goods_id] = item;
    });
    return newArr2;
  },
  // 扫码方法
  scanCode() {
    wx.scanCode({
      success: (res) => {
        if (res.scanType == "WX_CODE") {

          let scene = decodeURIComponent(res.path).split('scene=')[1];
          let info_arr = scene.split(",");
          console.log(scene, info_arr)
          for (let i = 0; i < info_arr.length; i++) {
            let chil_arr = [];
            chil_arr = info_arr[i].split("=");
            if (chil_arr[0] == 'id') {
              this.setData({
                goodsId: chil_arr[1]
              })
            }
            // 扫价签码，不是当前门店
            if (chil_arr[0] == 'store_id') {
              if (this.data.store_id) {
                if (chil_arr[1] != this.data.store_id) {
                  wx.showModal({
                    title: '提示',
                    content: '当前商品不属于此门店是否跳转到该门店',
                    complete: (resInfo) => {
                      if (resInfo.confirm) {
                        let url = '/packageI/storePriceTag/storePriceTagIndex/storePriceTagIndex';
                        for (let i = 0; i < info_arr.length; i++) {
                          if (i == 0) {
                            url += `?${info_arr[0]}`
                          } else {
                            url += `&${info_arr[i]}`
                          }
                        }
                        wx.redirectTo({
                          url: url,
                        })
                      }
                    }
                  })
                  return
                }
              }
              console.log('是当前门店的商品价签码')
              this.setData({
                store_id: chil_arr[1]
              })
            }
          }
          this.getGoodsDetail(this.data.goodsId)
          return
        }
        this.getGoodsDetail(res.result)
      }
    })
  },
  // 扫条形码获取商品详情
  getGoodsDetail(goodsId) {
    let urlStr = app.getNetAddresss('plugin.store-price-tag.frontend.goods.get-goods-page');
    app._postNetWork({
      url: urlStr,
      data: {
        id: goodsId
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if (res.data.get_store_info.store_id != this.data.store_id) {
            // 扫条形码，条形码商品不是当前门店的
            wx.showModal({
              title: '提示',
              content: '当前商品不属于此门店是否跳转到该门店',
              complete: (resInfo) => {
                if (resInfo.confirm) {
                  wx.redirectTo({
                    url: `/packageI/storePriceTag/storePriceTagIndex/storePriceTagIndex?store_id=${res.data.get_store_info.store_id}&id=${goodsId}`,
                  })
                }
              }
            })
            return
          }
          this.setData({
            goodsInfo: res.data.get_goods,
            goodsPopupShow: true
          })
        } else {
          wx.showToast({
            title: res.msg,
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  // 结算
  goodsOrder(){
    let val = this.data.goodsCarts;
    console.log(this.data.goodsCarts)
    this._goodsOrder(val);
  },
  _goodsOrder(val, status){
    let sum = 0;
    if (!status && !this.isHasDifferType(val)) {
      return;
    }
    this.data.carts.forEach(val => {
      sum += val.total;
    });
    if (sum == 0) {
      app.tips('请添加购买的商品')
      return;
    }
    if (val.length == 0 || this.data.carts.length == 0) {
      return;
    } else {
      wx.navigateTo({
        url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=store&store_id=' + this.data.store_id
      });
    }
  },
  isHasDifferType(data) {
    //门店购物车提交结算的时候，要判断当前购物车中是否同时存在普通商品和安装服务商品，如果同时存在，要弹框提示
    // 商品不是安装服务商品，直接没有live_install这个字段
    let open_state = 0; //有安装服务的商品
    let clone_state = 0; //没安装服务的商品
    let plugin_name = "";
    for (let item in data) {
      if (item.live_install && item.live_install.open_state == 1) {
        open_state += 1;
        plugin_name = item.live_install.plugin_name;
      } else {
        clone_state += 1;
      }
    }
    if (open_state != 0 && clone_state != 0) {
      //都有值说明存在 两种 不同商品类型，提示框显示
      wx.showModal({
        title: '提示',
        content: `普通商品与${plugin_name}商品一同下单将无法享受${plugin_name}，是否继续下单？`,
        success: (res) => {
          if (res.confirm) {
            this._goodsOrder(data, true);
          } else if (res.cancel) {
            console.log(res.cancel);
          }
        }
      });
      return false;
    }
    return true;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})